//
//  LLPortalViewController.m
//  lrlzapp
//
//  Created by dl on 16/2/22.
//  Copyright © 2016年 lrlz. All rights reserved.
//

#import "LLPortalViewController.h"
#import "LLPortalViewModel.h"
#import "LLMainViewController.h"

@interface LLPortalViewController ()

@property(strong, nonatomic) UIPageViewController *pageViewController;
@property(weak, nonatomic) IBOutlet HMSegmentedControl *segmentedControl;
@property(weak, nonatomic) IBOutlet NSLayoutConstraint *heightOfLineOnSeg;
@property(weak, nonatomic) IBOutlet UIView *contentView;
@property(weak, nonatomic) IBOutlet UIBarButtonItem *searchBtn;

@property(nonatomic, strong, readwrite) LLPortalViewModel *viewModel;
@end

@implementation LLPortalViewController
@dynamic viewModel;

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.viewModel = [[LLPortalViewModel alloc] init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.fd_prefersNavigationBarHidden = YES;
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor whiteColor], NSFontAttributeName : SUIT_FONT(17)};
    [self.navigationController.navigationBar lt_setBackgroundColor:UIColorFromRGB(0xF7509C)];

    self.segmentedControl.backgroundColor = [UIColor whiteColor];
    self.segmentedControl.textColor = UI_COLOR_FONT_BLACK;
    self.segmentedControl.selectionIndicatorColor = UI_COLOR_RED;
    self.segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
    self.segmentedControl.selectedTextColor = UI_COLOR_RED;
    self.segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleFullWidthStripe;
    self.segmentedControl.showVerticalDivider = NO;
    self.segmentedControl.font = SUIT_FONT(14);
    self.segmentedControl.selectionIndicatorHeight = 1.f + SUIT_LINE_WIDTH;
    self.segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
    self.heightOfLineOnSeg.constant = SUIT_LINE_WIDTH;

    UIPageViewController *pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll
                                                                               navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
                                                                                             options:nil];
    pageViewController.delegate = self;
    pageViewController.dataSource = self;
    [self addChildViewController:pageViewController];
    [_contentView addSubview:pageViewController.view];
    [pageViewController.view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
    [pageViewController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_contentView);
    }];
    self.pageViewController = pageViewController;
}

- (void)bindViewModel {
    [super bindViewModel];

    self.searchBtn.rac_command = self.viewModel.searchBtnCommand;
    @weakify(self)
    [[[RACObserve(self.viewModel, viewControllers)
            distinctUntilChanged]
            ignore:nil]
            subscribeNext:^(NSArray<LLViewController *> *viewControllers) {
                @strongify(self)
                if (viewControllers.count > 0) {
                    [self.segmentedControl setSelectedSegmentIndex:0 animated:NO];
                    [self.pageViewController setViewControllers:@[self.viewModel.viewControllers[0]]
                                                      direction:UIPageViewControllerNavigationDirectionForward
                                                       animated:NO
                                                     completion:NULL];
                }
            }];
    [[[RACObserve(self.viewModel, viewModels)
            distinctUntilChanged]
            ignore:nil]
            subscribeNext:^(NSArray<LLViewModel *> *viewModels) {
                NSArray *titles = [[viewModels.rac_sequence.signal
                        map:^id(LLViewModel *vm) {
                            return vm.segmentedTitle;
                        }] toArray];
                [self.segmentedControl setSectionTitles:titles];
            }];

    [self.viewModel.loadSegmentsCommand execute:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (UIViewController *)selectedController {
    return self.viewModel.viewControllers[[self.segmentedControl selectedSegmentIndex]];
}

#pragma mark - UIPageViewControllerDataSource

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
      viewControllerBeforeViewController:(LLViewController *)viewController {
    NSUInteger index = [self.viewModel.viewControllers indexOfObject:viewController];
    if ((index == NSNotFound) || (index == 0)) {
        return nil;
    }
    return self.viewModel.viewControllers[--index];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
       viewControllerAfterViewController:(LLViewController *)viewController {
    NSUInteger index = [self.viewModel.viewControllers indexOfObject:viewController];
    if ((index == NSNotFound) || (index + 1 >= [self.viewModel.viewControllers count])) {
        return nil;
    }
    return self.viewModel.viewControllers[++index];
}

- (void)pageViewController:(UIPageViewController *)viewController
        didFinishAnimating:(BOOL)finished
   previousViewControllers:(NSArray *)previousViewControllers
       transitionCompleted:(BOOL)completed {
    if (!completed) {
        return;
    }
    [self.segmentedControl setSelectedSegmentIndex:[self.viewModel.viewControllers indexOfObject:[viewController.viewControllers lastObject]]
                                          animated:YES];
}

- (IBAction)pageControlValueChanged:(id)sender {
    UIPageViewControllerNavigationDirection direction =
            [self.segmentedControl selectedSegmentIndex] > [self.viewModel.viewControllers indexOfObject:[self.pageViewController.viewControllers lastObject]]
                    ? UIPageViewControllerNavigationDirectionForward : UIPageViewControllerNavigationDirectionReverse;
    [self.pageViewController setViewControllers:@[[self selectedController]]
                                      direction:direction
                                       animated:YES
                                     completion:NULL];
}

@end
